package link

import (
	"github.com/gin-gonic/gin"
	"gohub/pkg/app"
	"gohub/pkg/cache"
	"gohub/pkg/database"
	"gohub/pkg/helpers"
	"gohub/pkg/paginator"
	"time"
)

// Get 通过手机号来获取用户
func Get(ID string) (model Link) {
	database.DB.Where("id=?", ID).First(&model)
	return
}

// All 获取所有用户数据
func All() (models []Link) {
	database.DB.Find(&models)
	return
}

// Paginate 分页内容
func Paginate(c *gin.Context, perPage int) (models []Link, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(&Link{}),
		&models,
		app.V1URL(database.TableName(&Link{})),
		perPage,
	)
	return
}

func AllCached() (links []Link) {
	cacheKey := "links:all"
	expireTime := 120 * time.Second
	cache.GetObject(cacheKey, &links)

	if helpers.Empty(links) {
		links = All()
		if helpers.Empty(links) {
			return links
		}
		cache.Set(cacheKey, links, expireTime)
	}
	return
}